$(function () {
    // 1. 业务视图页面元数据管理事件处理
    // 1.1.触发元数据集中管理视图
    $('body').on('click', ':not([data-meta-app])[data-meta-view]', function () {
        var params = BigUtil.parseData($(this), 'data-meta-');
        BigUtil.openTab({
            title: '元数据',
            url: '/meta/man/view',
            params: params
        });
    });

    // 1.2.dropdown点击后提交
    function postMeta(tag, url) {
        $('body').on('click', '[' + tag + ']', function () {
            var params = BigUtil.parseData($(this), 'data-meta-');
            if (params.cascade == 'true') {
                if (!confirm('该操作无法恢复，请谨慎操作！')) {
                    return;
                }
            }
            $.post(url, params, function (json) {
                if (json.success) {
                    MApp.refreshTab();
                } else {
                    alert(json.msg);
                }
            });
        });
    }

    // 移动视图属性
    postMeta('data-meta-moveviewproperty', '/meta/man/biz/viewproperty/move');
    // 隐藏视图属性
    postMeta('data-meta-hideviewproperty', '/meta/man/biz/viewproperty/hide');
    // 显示视图属性
    postMeta('data-meta-showviewproperty', '/meta/man/biz/viewproperty/show');
    // 删除视图属性
    postMeta('data-meta-deleteviewproperty', '/meta/man/biz/viewproperty/delete');
    // 设置大小
    postMeta('data-meta-resizeviewproperty', '/meta/man/biz/viewproperty/resize');
    // 排序
    postMeta('data-meta-orderviewproperty', '/meta/man/biz/viewproperty/order');
    // 取消排序
    postMeta('data-meta-unorderviewproperty', '/meta/man/biz/viewproperty/unorder');
    // 取消所有排序
    postMeta('data-meta-unorderview', '/meta/man/biz/view/unorder');
    // 改变排序
    postMeta('data-meta-toggleorderviewproperty', '/meta/man/biz/viewproperty/toggleorder');
    // 删除按钮
    postMeta('data-meta-deletebutton', '/meta/man/biz/button/delete');
    // 移动按钮
    postMeta('data-meta-movebutton', '/meta/man/biz/button/move');
    // 设置列表行数
    postMeta('data-meta-rows', '/meta/man/biz/list/setrows');
    // 取消分页
    postMeta('data-meta-unpage', '/meta/man/biz/list/unpage');

    // 1.3.dropdown点击后弹出modal
    function postMetaModal(modalSelector, url) {
        $('body').on('click', modalSelector + ' button:not([data-dismiss])', function () {
            var modal = $(this).parents('.modal:first');
            BigUtil.ajaxForm({
                formType: 'modal',
                form: modal,
                url: url,
                successFn: function (json) {
                    if (json.success) {
                        modal.modal('hide');
                        $('.modal-backdrop').remove();
                        MApp.refreshTab();
                    } else {
                        alert(json.msg);
                    }
                }
            });
        });
    }

    // 修改视图属性提交
    postMetaModal('[id$="-modal-update-viewproperty"]', '/meta/man/biz/viewproperty/update');
    // 设置类型选择radio
    $('body').on ('click', '[id$="-modal-update-viewproperty"] :radio[name=type]', function() {
        $('[id$="-modal-update-viewproperty"] [name=customtype]').val($(this).val());
    });
    // 创建属性提交
    postMetaModal('[id$="-modal-create-property"]', '/meta/man/biz/viewproperty/createproperty');
    // 创建数据字典
    postMetaModal('[id$="-modal-create-dictionary"]', '/meta/man/biz/viewproperty/createdictionary');

    // 创建关系时，类型选择事件
    $('body').on('click', '[id$="-modal-create-relation"] input[name=type]', function () {
        var relatedObjectId = $(this).parents('.modal').find('input[name=relatedobjectid]');
        var single = relatedObjectId.attr('data-app-selectorsingle');
        if ($(this).val().indexOf('C') > 0) {
            if (single == 'true') {
                relatedObjectId.attr('data-app-selectorsingle', 'false');
            }
        } else {
            if (single == 'false') {
                relatedObjectId.attr('data-app-selectorsingle', 'true');
                var buttons = relatedObjectId.parents('.form-group').find('button');
                if (buttons.length > 1) {
                    relatedObjectId.val('');
                    buttons.remove();
                }
            }
        }
    });
    postMetaModal('[id$="-modal-create-relation"]', '/meta/man/biz/viewproperty/createrelation');
    // 创建按钮
    postMetaModal('[id$="-modal-create-button"]', '/meta/man/biz/button/create');

    // 2.元数据首页（对象列表）
    // 跳转对象元数据集中管理页面
    $('body').on('click', 'a.small-box-footer[data-meta-objectid]', function () {
        BigUtil.openTab({
            title: $(this).parent().find('h4 strong').text(),
            url: '/meta/man/object',
            params: BigUtil.parseData($(this), 'data-meta-')
        });
    });

    // 设置对象进入元数据管理状态
    $('body').on('click', '.small-box button[data-meta-objectid]', function () {
        var id = $(this).attr("data-meta-objectid");
        $.ajax({
            url: '/meta/man/setMeta?id=' + id,
            data: id,
            dataType: "json",
            success: function (msg) {
            }
        });
    });

    // 设置所有对象元数据管理状态
    $('body').on('click', '#metaAll', function () {
        $.post('/meta/man/setMetaAll', function (json) {
        	alert(json.msg)
        });
    });
    
 // 设置所有对象元数据管理状态
    $('body').on('click', '#unMetaAll', function () {
        $.post('/meta/man/unsetMetaAll', function (json) {
        	alert(json.msg)
        });
    });
    
    // 导入领域模型excel
    $('body').on('click', '#ImportExcel', function () {
        BigUtil.openTab({
            title: "导入领域模型",
            url: '/meta/man/loadMetaImport'
        });
    });

    // AJAX请求
    $('body').on('click', '[meta-btn-import]', function () {
        var data = new FormData($("#meta-addForm")[0]);
        $.ajax({
            url: "/meta/man/importExcel",
            type: "post",
            data: data,
            cache: false,
            processData: false,
            contentType: false,
            dataType: "json",
            success: function (json) {
                alert(json.msg);
            }
        });
    });

    // 添加对象
    $('body').on('click', '#AddObject', function () {
        BigUtil.openTab({
            title: "添加对象",
            url: '/meta/man/loadMetaAddObject',
            fn: function () {
                BigUtil.initMultiple({
                    multiple: '[data-meta-objectpropertyconfig] input[type=hidden]',
                    refreshValue: function (hidden) {
                        // 当字段内容变化时，更新hidden的value值
                        var data = [];
                        hidden.siblings('.input-group').each(function () {
                            var inputGroup = $(this);
                            var value = inputGroup.children().eq(0).val();
                            if (BigUtil.isEmpty(value)) {
                                return;
                            }
                            data.push(value);
                        });
                        hidden.val(JSON.stringify(data));
                    }
                });
            }
        });
    });

    $('body').on('click', '[meta-add-btn-object]', function () {

        var data = new FormData($("#meta-man-add-object")[0]);
        $.ajax({
            url: "/meta/man/loadMetaAddObject",
            type: "post",
            data: data,
            cache: false,
            processData: false,
            contentType: false,
            dataType: "json",
            success: function (msg) {
                alert("success");
                window.location.reload();
            }
        });
    });

    // 添加工作流
    $('body').on('click', '#AddWorkflow', function () {
        BigUtil.openTab({
            title: "添加工作流",
            url: '/meta/man/loadMetaAddWorkflow',
            fn: function () {
                BigUtil.initMultiple({
                    multiple: '[data-meta-objectpropertyconfig] input[type=hidden]',
                    refreshValue: function (hidden) {
                        // 当字段内容变化时，更新hidden的value值
                        var data = [];
                        hidden.siblings('.input-group').each(function () {
                            var inputGroup = $(this);
                            var value = inputGroup.children().eq(0).val();
                            if (BigUtil.isEmpty(value)) {
                                return;
                            }
                            data.push(value);
                        });
                        hidden.val(JSON.stringify(data));
                    }
                });
            }
        });
    });

    //追加属性对象输入框
    $('body').on('click', '[meta-add-workflow-append-attribute-configuration]', function () {
        var taskHtml = " <div class=\"form-group\" data-meta-objectpropertyconfig >\n" +
            "                            <label class=\"control-label\">任务配置:\n" +
            "                                <button meta-add-workflow-append-attribute-configuration class=\"btn fa fa-plus btn-primary\" style=\"border-radius:5px;\" type=\"button\"></button>\n" +
            "                                <button meta-add-workflow-delete-attribute-configuration class=\"btn fa fa-minus btn-danger\" style=\"border-radius:5px;\" type=\"button\"></button>\n" +
            "                            </label>\n" +
            "                            <input class=\"form-control\" name=\"objectPropertyConfig\" placeholder=\"请输入任务名称\" required>\n" +
            "                            <input type=\"hidden\" name=\"objectPropertyConfig\">\n" +
            "                            <div class=\"input-group\">\n" +
            "                                <input class=\"form-control\" placeholder=\"请输入属性的配置\" required>\n" +
            "                                <span class=\"input-group-addon\" >+</span>\n" +
            "                                <span class=\"input-group-addon bg-red\">-</span>\n" +
            "                            </div>\n" +
            "                        </div>";
        var task = $(taskHtml).appendTo(".meta-add-workflow-attribute-configuration");
        BigUtil.initMultiple({
            multiple: task.find('input[type=hidden]'),
            refreshValue: function (hidden) {
                // 当字段内容变化时，更新hidden的value值
                var data = [];
                hidden.siblings('.input-group').each(function () {
                    var inputGroup = $(this);
                    var value = inputGroup.children().eq(0).val();
                    if (BigUtil.isEmpty(value)) {
                        return;
                    }
                    data.push(value);
                });
                hidden.val(JSON.stringify(data));
            }
        });
    });

    //删除属性对象输入框
    $('body').on('click', '[meta-add-workflow-delete-attribute-configuration]', function () {

        if ($("[meta-add-workflow-delete-attribute-configuration]").siblings().length > 1) {
            $(this).parent().parent().remove();
        } else {

        }
    });


    $('body').on('click', '[meta-add-btn-Workflow]', function () {
        var data = new FormData($("#meta-add-Workflow")[0]);
        alert(JSON.stringify(data))
        $.ajax({
            url: "/meta/man/loadMetaAddWorkflow",
            type: "post",
            data: data,
            cache: false,
            processData: false,
            contentType: false,
            dataType: "json",
            success: function (msg) {
                alert("success");
                window.location.reload();
            }
        });
    });

    // meta-dropdown中的应用预览点击事件
    $('body').on('click', '.dropdown-menu a.fa-binoculars', function () {
        MApp.createTab(MApp.parseData($(this)), $(this).text());
    });

    // meta-dropdown中的删除点击事件
    $('body').on('click', '[data-object-delete]', function () {
        $.post('/meta/man/object/delete', {id: $(this).attr('data-object-delete')}, function (json) {
            if (json.success) {
                MApp.refreshTab();
            } else {
                alert(json.msg);
            }
        });
    });

    // meta-dropdown中的应用删除点击事件
    $('body').on('click', '[data-app-delete]', function () {
        $.post('/meta/man/app/delete', {id: $(this).attr('data-app-delete')}, function (json) {
            if (json.success) {
                MApp.refreshTab();
            } else {
                alert(json.msg);
            }
        });
    });

    // meta-dropdown中的应用拷贝点击事件
    $('body').on('click', '[data-app-copy]', function () {
        $.post('/meta/man/app/copy', {id: $(this).attr('data-app-id')}, function (json) {
            if (json.success) {
                MApp.refreshTab();
            } else {
                alert(json.msg);
            }
        });
    });

    // meta-dropdown中的应用‘创建leditor’点击事件
    $('body').on('click', '[data-app-create-leditor]', function () {
        $.post('/meta/man/app/createLeditor', {id: $(this).attr('data-app-id')}, function (json) {
            if (json.success) {
                MApp.refreshTab();
            } else {
                alert(json.msg);
            }
        });
    });

    // meta-dropdown中的应用创建菜单点击事件
    $('body').on('click', '.dropdown-menu a.fa-navicon', function () {
        MApp.clickBtnOpenTab($(this), null, null, false, {
            id: 'crudx_sys_menu',
            type: 'crud',
            'sys_menu_app_id': $(this).attr('data-app-id'),
            'sys_menu_type': 1
        });
    });

    // 3.对象元数据集中管理页面事件处理
    function parseData(jqObj) {
        var objectId = $('table[data-meta-po=MObject]').find('td:nth-child(2)').eq(0).text().trim();
        var table = jqObj.parents('table:first');
        var po = table.attr('data-meta-po');
        var id = table.find('td:nth-child(2)').eq(0).text().trim();
        var tr = jqObj.parents('tr:first');
        var property = tr.find('td:first').text().trim();
        var value = tr.find('input').val();
        if (tr.find('td:first input').length == 1) {
            property = tr.find('td:first input').val();
            value = tr.find('td:nth-child(2) input').val();
        }
        return {
            objectId: objectId,
            po: po,
            id: id,
            property: property,
            value: value
        };
    }

    $('body').on('click', '[data-meta-save]', function () {
        var params = parseData($(this));
        if (BigUtil.isEmpty(params.value)) {
            alert('值不能为空！');
            return;
        }
        $.post('/meta/man/save' + params.po, params, function (json) {
            if (json.success) {
            } else {
                alert(json.msg);
            }
        });
    });
    $('body').on('click', '[data-meta-add]', function () {
        var params = parseData($(this));
        if (BigUtil.isEmpty(params.value) || BigUtil.isEmpty(params.property)) {
            alert('属性和值都不能为空！');
            return;
        }
        $.post('/meta/man/add' + params.po, params, function (json) {
            if (json.success) {
                var html = ['<tr>',
                    '<td>' + params.property + '</td>',
                    '<td><input class="form-control input-sm" value="' + params.value + '"></td>',
                    '<td>',
                    '<div class="btn-group btn-xs">',
                    '<button type="button" class="btn btn-xs" data-meta-save>Save</button>',
                    '<button type="button" class="btn btn-xs" data-meta-delete>Delete</button>',
                    '</div>',
                    '</td>',
                    '</tr>'].join('');
                $(this).parents('tr:first').before(html);
            } else {
                alert(json.msg);
            }
        });
    });
    $('body').on('click', '[data-meta-delete]', function () {
        if (!confirm('确定要删除该属性吗？')) {
            return;
        }
        var params = parseData($(this));
        $.post('/meta/man/delete' + params.po, params, function (json) {
            if (json.success) {
                $(this).parents('tr:first').remove();
            } else {
                alert(json.msg);
            }
        });
    });

    $('body').on('click', '[data-meta-addMPropertyOrMRelation]', function () {
        var params = parseData($(this));
        var tr = $(this).parents('tr').eq(0);
        var prop = tr.find('[name=prop]').val();
        var propConfig = tr.find('[name=propconfig]').val();
        if (BigUtil.isEmpty(propConfig)) {
            alert('配置信息不能为空！');
            return;
        }
        $.post('/meta/man/addMPropertyOrMRelation', {
            prop: prop,
            propConfig: propConfig,
            objectId: params.objectId
        }, function (json) {
            if (json.success) {
                BigUtil.refreshTab();
            } else {
                alert(json.msg);
            }
        });
    });

    $('body').on('click', '[data-meta-addMViewPropertyByMProperty]', function () {
        var params = parseData($(this));
        var tr = $(this).parents('tr').eq(0);
        var propertyId = tr.find('select[name=propertyId]').val();
        var viewPropertyType = tr.find('select[name=viewPropertyType]').val();
        var viewPropertyConfig = tr.find('textarea[name=viewPropertyConfig]').val();
        $.post('/meta/man/addMViewPropertyByMProperty', {
            propertyId: propertyId,
            viewPropertyType: viewPropertyType,
            viewPropertyConfig: viewPropertyConfig,
            viewId: params.id
        }, function (json) {
            if (json.success) {
                BigUtil.refreshTab();
            } else {
                alert(json.msg);
            }
        });
    });

    $('body').on('click', '[data-meta-addMViewPropertyByMRelation]', function () {
        var params = parseData($(this));
        var tr = $(this).parents('tr').eq(0);
        var relationId = tr.find('select[name=relationId]').val();
        var viewPropertyType = tr.find('select[name=viewPropertyType]').val();
        var viewPropertyConfig = tr.find('textarea[name=viewPropertyConfig]').val();
        $.post('/meta/man/addMViewPropertyByMRelation', {
            relationId: relationId,
            viewPropertyType: viewPropertyType,
            viewPropertyConfig: viewPropertyConfig,
            viewId: params.id
        }, function (json) {
            if (json.success) {
                BigUtil.refreshTab();
            } else {
                alert(json.msg);
            }
        });
    });

});